use crate::handler::handler::send_response;
use crate::pkg::errno::code::Errno::{ErrDatabase, ErrModulesNotFound, IsOk};
use actix_web::{web, Responder, Result};

use crate::model::modules;
use crate::model::request::{ModulesEdit, ModulesInfo, ModulesSearch, ID};
use crate::model::response::ModulesDetailAll;
use crate::model::task;

// 创建 modules
pub async fn create(t: web::Json<ModulesInfo>) -> Result<impl Responder> {
    // 1.新增
    let create_t = modules::create_modules(t.0).await;
    match create_t {
        Ok(_) => send_response(IsOk, Some(())).await,
        Err(e) => {
            println!("modules create {:#?}", e);
            send_response(ErrDatabase, None).await
        }
    }
}

// 编辑
pub async fn edit(params: web::Json<ModulesEdit>) -> Result<impl Responder> {
    // 判断id 是否存在
    if params.modules_detail.id.is_some() {
        // 查询 id是否存在
        let resp = modules::get_modules_detail(params.modules_detail.id.unwrap()).await;
        match resp {
            Ok(_) => {
                let edit_res = modules::edit_modules(params.0).await;
                match edit_res {
                    Ok(_) => send_response(IsOk, Some(())).await,
                    Err(_) => send_response(ErrDatabase, None).await,
                }
            }
            Err(_) => send_response(ErrModulesNotFound, None).await,
        }
    } else {
        send_response(ErrModulesNotFound, None).await
    }
}

// 列表
pub async fn list(params: web::Query<ModulesSearch>) -> Result<impl Responder> {
    let list = modules::get_modules_list(&params).await;
    match list {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}

// 详情
pub async fn detail(params: web::Path<ID>) -> Result<impl Responder> {
    let detail = modules::get_modules_detail(params.id).await;
    match detail {
        Ok(i) => {
            // 获取task
            let task_res = task::get_task_detail(i.id).await;
            match task_res {
                Ok(t) => {
                    let resp = ModulesDetailAll {
                        modules_detail: i,
                        task_list: t,
                    };
                    send_response(IsOk, Some(resp)).await
                }
                Err(e) => {
                    send_response(ErrModulesNotFound, None).await
                }
            }
        }
        Err(_) => send_response(ErrModulesNotFound, None).await,
    }
}
